package core;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import utility.Utility;

public class ConnectedClientThread extends Thread {

	Socket client;

	ObjectOutputStream out;
	ObjectInputStream in;
	
	public ConnectedClientThread(Socket client) {
		this.client = client;
		
		try {
			this.out = new ObjectOutputStream(this.client.getOutputStream());
			this.out.flush();
			this.in = new ObjectInputStream(this.client.getInputStream());
			this.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("IO EXCEPTION ERROR!");
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		
		String message = Utility.readSocketMessage(this.in);
				
		boolean close = false;
		while(!message.equals(NetProtocoll.BYE) && !message.equals(NetProtocoll.ERROR) && !close)
		{
			if(message.startsWith(NetProtocoll.LOGIN))
				if(this.login(message.substring(NetProtocoll.LOGIN.length())))
				{
					close = true;
					break;
				}
			
			message = Utility.readSocketMessage(this.in);
		}

		if(!close)
			this.close();
	}
	
	protected boolean login(String msg)
	{
		String[] parameter = msg.split(";");
		if(Function.clientLogin(parameter[0], parameter[1]))
		{
			Utility.sendSocketMessage(NetProtocoll.LOGINOK, this.out);
			ConnectionListener.getInstance().login(parameter[0], this.client, this.in, this.out);
			
			return true;
		} 

		Utility.sendSocketMessage(NetProtocoll.LOGINFAILED, this.out);
		return false;
	}
	
	public void close()
	{
		try {
			Utility.sendSocketMessage(NetProtocoll.BYE, this.out);
			this.client.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
